import Web3 from 'web3'
import USDT from './bnbUsdt.json'
import DAPP from './dapp.json'
import store from '../store'
import { Toast } from 'vant';
//正式
const ADDRESS_DAPP ="0x547e17Df9aaB0F7c0aF1499D69B7D24b0c7943d3"
const ADDRESS_USDT ="0x55d398326f99059fF775485246999027B3197955"
const ADDRESS_HULU ="0x7c10f1773EE1dbc40C5fAc75E7B7400c00A5439F"
const get_USDT="0x3bACDcd6f2F6ddbE10d87B27A5baD7E6F460B6B5"
const get_BNB ="0xBf18F2F9e74DaF8B2d95577E6f525Fc9b7da3852"


let ethereum = window.ethereum
    let i = setInterval(() => {
    if ((typeof window.ethereum) !== 'undefined') {
        ethereum = window.ethereum      
        handleWatch()  
        clearInterval(i)  
    }
    }, 1000);

export async function set(){
            let web3s = new Web3(ethereum);
            window.utilWeb3 = web3s.utils;
            window.ContractEth = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP, {
            from: ethereum.selectedAddress            
        });
}
export async function handleWatch () {
    if (!window.ethereum) {
        console.log('Metamask is not installed!')
        return false
      }
    window.ethereum.on('accountsChanged',  (accounts) => {
      if(accounts[0]){
        // let web3s = new Web3(ethereum);
        // let msg = web3s.utils.keccak256('授权签名');
        // let ht= await web3s.eth.sign(msg, accounts[0])
        // .then(res=>{return res});  
        // if(ht){
      sessionStorage.setItem('userWallet',accounts[0])  
      store.commit("userWallet", accounts[0]);  
    }else{
        sessionStorage.removeItem('userWallet')
      }     
    })
  }
export async function connectTron() {  
    let web3s = new Web3(ethereum);
    if (web3s.utils.toDecimal(ethereum.chainId)!='0x38') {
        try {
            await window.ethereum.request({
                method: 'wallet_switchEthereumChain',
                params: [{
                    chainId: Web3.utils.numberToHex(56), // 目标链ID
                }]
            })
        } catch (e) {
            if (e.code == 4902) {
                try {
                    await window.ethereum.request({
                        method: 'wallet_addEthereumChain',
                        params: [{
                            chainId: Web3.utils.numberToHex(56), // 目标链ID
                            chainName: 'Arbitrum One',
                            nativeCurrency: {
                                name: 'BNB',
                                symbol: 'BNB',
                                decimals: 18
                            },
                            rpcUrls: ['https://arbitrum-mainnet.infura.io'], // 节点
                            blockExplorerUrls: ['https://explorer.arbitrum.io']
                        }]
                    })
                    return true
                } catch (ee) {
                }
            } else if (e.code === 4001) return false
        }    
    }
    let isWallet =""
    if (window.ethereum) {
      try {
        await  window.ethereum.request({
          method: 'wallet_requestPermissions',
          params: [{ eth_accounts: {} }]
        }).then(accounts => {
          isWallet=accounts
        }).catch(error => {
          console.error('用户拒绝授权或发生错误:', error);
        });
      } catch (error) {
        isWallet=true
      }    
    }
  // store.commit("userWallet", eth_requestAccounts[0]);
    if(isWallet){
      const eth_requestAccounts= await ethereum.request({ method: "eth_requestAccounts" });
    return eth_requestAccounts
    }

}

// 签名认证
export function Sign(address) {
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let msg = web3s.utils.utf8ToHex('Welcome to Dapp');
         // //console.log(msg,address);
        let ht= await web3s.eth.personal.sign(msg, address)
        .then(res=>{return res}).catch(err=>{
          // Toast(err)
           // //console.log(err);
          return false});
       return ht?ht:false
  };
  return run();
  }
  
  // 授权USDT
export function toApprove(address,num) {
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(USDT, ADDRESS_USDT);  
        let amount = web3s.utils.toWei(num + '','ether');
        let gas = await web3s.eth.getGasPrice();
        let result = await unioContract.methods.approve(ADDRESS_DAPP, amount).send({from:address,gasPrice:gas}).catch(err => {
             // //console.log(err.message)
         return false
      });
      if(result){
        return result.transactionHash
    }else{
        return false
    }
    };
    return run();
  }
  export function getProved(address) {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(USDT, ADDRESS_USDT, {
              from:address
          });
          let result = await unioContract.methods.allowance(address,ADDRESS_DAPP).call()/(10**18);
         return result 
    };
    return run();
  }
   // 授权Hulu
export function toApproves(address,num) {
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(USDT, ADDRESS_HULU);  
        let amount = web3s.utils.toWei(num + '','ether');
        let gas = await web3s.eth.getGasPrice();
        let result = await unioContract.methods.approve(ADDRESS_DAPP, amount).send({from:address, gasPrice:gas}).catch(err => {
             // //console.log(err.message)
         return false
      });
      if(result){
        return result.transactionHash
    }else{
        return false
    }
    };
    return run();
  }
  export function getProveds(address) {
    let run = async () => {
        ethereum?set():""
          let web3s = new Web3(ethereum);
          let unioContract = await new web3s.eth.Contract(USDT, ADDRESS_HULU, {
              from:address
          });
          let result = await unioContract.methods.allowance(address,ADDRESS_DAPP).call()/(10**18);
         return result 
    };
    return run();
  }
// 绑定邀请人 0x0000000000000000000000000000000000000001
export  function bindInviter(address,referrer){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.bindReferrer(referrer).send({from:address, gasPrice:gas}).catch(err => {
            return false
        });
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}

// 动态划转
export function toTransDong(address) {
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
        let gas = await web3s.eth.getGasPrice();
        let result = await unioContract.methods.transDong().send({from:address, gasPrice:gas}).catch(err => {
         return false
      });
      if(result){
        return result.transactionHash
    }else{
        return false
    }
    };
    return run();
  }

// 余额互转
export function toTransEx(address,tadd,num) {
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
        let amount = web3s.utils.toWei(num + '','ether');
        let gas = await web3s.eth.getGasPrice();
        let result = await unioContract.methods.transEx(tadd,amount).send({from:address, gasPrice:gas}).catch(err => {
         return false
      });
      if(result){
        return result.transactionHash
    }else{
        return false
    }
    };
    return run();
  }

// 提现
export  function toWithdrawal(address){
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);
       let gas =await web3s.eth.getGasPrice()
        let result = await unioContract.methods.withdrawal().send({from:address, gasPrice:gas}).catch(err => {
            return false
        });
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();
}
// 用户卖出
export function toSell(address,num) {
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
        let amount = web3s.utils.toWei(num + '','ether');
        let gas = await web3s.eth.getGasPrice();
        console.log(num);
        let result = await unioContract.methods.sell(amount).send({from:address, gasPrice:gas}).catch(err => {
         return false
      });
      if(result){
        return result.transactionHash
    }else{
        return false
    }
    };
    return run();
  }
  // 用户余额卖出
export function toSellDappAmount(address,num) {
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
        let amount = web3s.utils.toWei(num + '','ether');
        let gas = await web3s.eth.getGasPrice();
        console.log(num);
        let result = await unioContract.methods.sellDappAmount(amount).send({from:address, gasPrice:gas}).catch(err => {
         return false
      });
      if(result){
        return result.transactionHash
    }else{
        return false
    }
    };
    return run();
  }
  
//   获取产品列表 返回的列表数组下标从0开始
  export async function getProducts() {  
    let run = async () => {
    ethereum?set():""
     let web3s = new Web3(ethereum); 
     let unioContract= await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
    let result = await unioContract.methods.getProducts().call(); 
   return result
  };
  return run();
}
// 获取USDT
export async function getMyUsdt(address) {  
    let run = async () => {
     let web3s = new Web3(ethereum); 

     let unioContract= await new web3s.eth.Contract(USDT, ADDRESS_USDT);  
    let result = await unioContract.methods.balanceOf(address).call(); 
    if(result){
        return  web3s.utils.fromWei(result+'', 'ether');
    }else{
        return 0
    }
  };
  return run();
}
// 获取Hulu
export async function getMyHulu(address) {  
    let run = async () => {
     let web3s = new Web3(ethereum); 

     let unioContract= await new web3s.eth.Contract(USDT, ADDRESS_HULU);  
    let result = await unioContract.methods.balanceOf(address).call(); 
    if(result){
        return  web3s.utils.fromWei(result+'', 'ether');
    }else{
        return 0
    }
  };
  return run();
}
// 创建订单
export function toBookOrder(address,pid,type) {
    let run = async () => {
        ethereum?set():""
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
        let gas = await web3s.eth.getGasPrice();
        console.log(pid,type);
        let result = await unioContract.methods.bookOrder(pid,type).send({from:address, gasPrice:gas}).catch(err => {
         return false
      });
      if(result){
        return result.transactionHash
    }else{
        return false
    }
    };
    return run();
  }

//   获取订单
export async function getOrders(address,type) {  
    let run = async () => {
    ethereum?set():""
     let web3s = new Web3(ethereum); 
     let unioContract= await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
    let result = await unioContract.methods.getOrders(address,type).call(); 
   return result
  };
  return run();
}
// 用户基础信息
export async function getUser(address) {  
    let run = async () => {
    ethereum?set():""
     let web3s = new Web3(ethereum); 
     let unioContract= await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
    let result = await unioContract.methods.users(address).call(); 
   return result
  };
  return run();
}
// 用户收益信息
export async function getUserInfo(address) {  
    let run = async () => {
    ethereum?set():""
     let web3s = new Web3(ethereum); 
     let unioContract= await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
    let result = await unioContract.methods.userInfos(address).call(); 
   return result
  };
  return run();
}
// 获取价格
export async function getPrice() {  
    let run = async () => {
    ethereum?set():""
     let web3s = new Web3(ethereum); 
     let unioContract= await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
    let ratio = await unioContract.methods.ratio().call(); 
   return 1*ratio/1000000
  };
  return run();
}


//   获取推荐关系
export async function getDirectReferralsInfo(address) {  
    let run = async () => {
    ethereum?set():""
     let web3s = new Web3(ethereum); 
     let unioContract= await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
    let result = await unioContract.methods.getDirectReferralsInfo(address).call(); 
   return result
  };
  return run();
}



// 首页数据
export async function getData() {  
    let run = async () => {
    ethereum?set():""
     let web3s = new Web3(ethereum); 
     let unioContract= await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
     let unioContract2= await new web3s.eth.Contract(USDT, ADDRESS_HULU); 
     
     let r1 = await unioContract2.methods.totalSupply().call();   
     let r2 = await unioContract.methods.td2().call();      
    let r3= await unioContract.methods.td1().call(); 
    let r4 = await unioContract.methods.jjpool().call(); 
    let r5 = await unioContract2.methods.balanceOf(ADDRESS_DAPP).call();  
    
    // console.log(r1,r2,r3,r4);
   return {r1,r2:r2.data3,r2s:r2.data3U,r3:r3.data5,r3s:r3.data4,r4:r4.totalPool,r4s:r4.grantPool,r5:r5}
  };
  return run();
}


export async function getPriceList() {  
    let run = async () => {
    ethereum?set():""
     let web3s = new Web3(ethereum); 
     let unioContract= await new web3s.eth.Contract(DAPP, ADDRESS_DAPP);  
    let result = await unioContract.methods.getRatios().call(); 
   return result
  };
  return run();
}






























































export  function upnode(address,num){
    let run = async () => {
        let web3s = new Web3(ethereum);
        let gas =await web3s.eth.getGasPrice()
        // console.log("gas",gas);
        let unioContract = await new web3s.eth.Contract(USDT, ADDRESS_USDT);
       let amount = web3s.utils.toWei(num + '', 'ether');
    
        let result = await unioContract.methods.transfer(get_USDT,amount).send({from:address, gasPrice:gas}).catch(err => {
            Toast(err.message)
            return false
        });
        console.log(result);
        // let result = await unioContract.methods.balanceOf(address).call()/(10 ** 18);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();

}

export  function transfers(address,amount){
    let run = async () => {
        let web3s = new Web3(ethereum);
        let unioContract = await new web3s.eth.Contract(ABIS, ADDRESS_ETH, {
            from:address
        });
       amount = web3s.utils.toWei(amount + '', 'ether');
       let gas = web3s.eth.getGasPrice()
       console.log("gas",gas);
        let result = await unioContract.methods.transfer(get_Batpl,amount).send({from:address,
            gasPrice:gas
        }).catch(err => {
            Toast(err.message)
        });
        // let result = await unioContract.methods.balanceOf(address).call()/(10 ** 18);
        if(result){
            return result.transactionHash
        }else{
            return false
        }
  };
  return run();

}

//BNB公募
export function transferBnb(address,price) {
    let run = async () => {
        let web3s = new Web3(ethereum);
    let amount = web3s.utils.toWei(price+'', 'ether');
    let gas =await web3s.eth.getGasPrice()
    console.log(amount);
        let result=await  web3s.eth.sendTransaction({
           from:address,
           to:get_BNB,
           value:amount,
           gasPrice:gas
       }).then(res=>{
           return res.transactionHash
       }).catch(()=>{ })
       return result  
  };
  return run();
}

//BNB公募
export function transferBnbs(address,price) {
    let run = async () => {
        let web3s = new Web3(ethereum);
    let amount = web3s.utils.toWei(price+'', 'ether');
        let result=await  web3s.eth.sendTransaction({
           from:address,
           to:get_USDT,
           value:amount
       }).then(res=>{
           return res.transactionHash
       }).catch(()=>{ })
       return result  
  };
  return run();
}

//HT转账
export function transferHt(address) {
    let run = async () => {
        let web3s = new Web3(ethereum);
        let msg = web3s.utils.keccak256('授权签名');
        let ht= await web3s.eth.sign(msg, address).then(res=>{return res}).catch(()=>{return false});  
       return ht  
  };
  return run();
}


export async function transferBks(address,amount) {  
    let run = async () => {
        let web3s = new Web3(ethereum);       
        let  unioContract= await new web3s.eth.Contract(BK, ADDRESS_BK);
            amount =web3s.utils.toWei(amount+'', 'gwei'); //amount*10**9;  
            
            console.log('-------',amount);               
    let result = await unioContract.methods.transfer(get_Join,amount).send({from:address}).catch(err => {
        console.log(err.message)
    });
    if(result){
        return result.transactionHash
    }else{
        return false
    }
  };
  return run();
}

export async function transferBk(address,amount) {  
    let run = async () => {
        let web3s = new Web3(ethereum);       
        let  unioContract= await new web3s.eth.Contract(BK, ADDRESS_BK);
            amount =web3s.utils.toWei(amount+'', 'gwei'); //amount*10**9;  
            
            console.log('-------',amount);               
    let result = await unioContract.methods.transfer(get_USDT,amount).send({from:address}).catch(err => {
        console.log(err.message)
    });
    if(result){
        return result.transactionHash
    }else{
        return false
    }
  };
  return run();
}

export async function transferCake(address,amount) {  
    let run = async () => {
        let web3s = new Web3(ethereum);       
        let unioContract= await new web3s.eth.Contract(CAKE, ADDRESS_CAKE); 
                amount = web3s.utils.toWei(amount+'', 'ether');
                
    let result = await unioContract.methods.transfer(get_USDT,amount).send({from:address}).catch(err => {
        console.log(err.message)
    });
    if(result){
        return result.transactionHash
    }else{
        return false
    }
  };
  return run();
}


export async function transferTypes(type,address,amount){
    if(type==1){
       let result =await transferBk(address,amount).then(res=>{
        return res}).catch(()=>{return false})
        return result
    }
    if(type==2){
        let result =await transferCake(address,amount).then(res=>{
            return res}).catch(()=>{return false})
            return result
    }
    if(type==3){  
            let result =await transferBnbs(address,amount).then(res=>{
                return res}).catch(()=>{return false})
                return result
    }
}











